// 扩展 day.js 的插件
dayjs.extend(dayjs_plugin_utc)
dayjs.extend(dayjs_plugin_timezone)

const apiPath = '/api/ip/'

let page = 1
let totalPage = 1 // 初始总页数
const pageSize = 10

const $todayIP = $('#todayIP')
const $paginationDom = $('#paginationDom')
const $loadingDom = $('#loading-dom')

const uap = new UAParser()
let ipArray = []

// 通过IP获取地址
async function getAddress(arr) {
	if (!arr) {
		return { code: 400, data: null, msg: '数组不得为空' }
	}

	if (arr.length === 0) {
		return { code: 200, data: [], msg: '没有数据' }
	}

	const array = arr.map(item => {
		return {
			query: item.ip
		}
	})
	
	try {
		const response = await fetch(`${apiPath}getAddress`, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
			},
			body: JSON.stringify(array)
		})

		const data = await response.json()

		return data
	} catch (error) {
		console.error('接口有误:', error)
		return { code: 500, data: error, msg: '接口有误' }
	}
}

async function getTableAddress() {
	try {
		// 遮罩
		$loadingDom.lyearloading({
			opacity: 0.5,
			backgroundColor: '#ccc',
			textColorClass: 'text-info',
			spinnerColorClass: 'text-info',
			spinnerSize: 'lg',
			spinnerText: '地址获取中...',
			zindex: 9999
		})

		const result = await getAddress(ipArray)

		if (result.code !== 200) {
			showNotify(result.msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}
		console.log(result.data);
		
		result.data.forEach((item, index) => {
			const $dom = $(`.xf_ip_${index} span`)
			$dom.text(item.status === 'success' ? `【${item.country} ${item.city}】` : `【未查询到此IP地址】`)
		})

		showNotify(result.msg, 'success', 5000, 'mdi mdi-alert', 'top', 'right')
		$loadingDom.hide()
	} catch (error) {
		$loadingDom.hide()
		console.error('地址获取失败: ', error)
		showNotify('服务器有误, 地址获取失败', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
}


// 获取 IP 数据
async function getIp(str, page = 1) {
	if (!str) {
		$todayIP.html(`<tr><td colspan="6" class="text-center">参数不得为空</td></tr>`)
		return
	}

	// 遮罩
	$loadingDom.lyearloading({
		opacity: 0.5,
		backgroundColor: '#ccc',
		textColorClass: 'text-info',
		spinnerColorClass: 'text-info',
		spinnerSize: 'lg',
		spinnerText: '加载中...',
		zindex: 9999
	})

	ipArray = []

	try {
		const response = await $.ajax({
			url: `${apiPath}get?isTady=${str}&page=${page}&pageSize=${pageSize}`,
			method: 'GET',
			dataType: 'json'
		})

		const { code, msg } = response

		if (code !== 200) {
			$loadingDom.hide()
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			$todayIP.html(`<tr><td colspan="6" class="text-center">${msg}</td></tr>`)
			return
		}

		const { data: { data, total } } = response

		let tr = ''

		if (data.length < 1) {
			$loadingDom.hide()
			$todayIP.html(`<tr><td colspan="6" class="text-center">暂无IP数据</td></tr>`)
			return
		}

		// 临时方法: 添加ip
		data.forEach(item => {
			ipArray.push({
				id: item.id,
				ip: item.ip
			})
		})

		// const addresResult = await getAddress(ipArray)

		// if (addresResult.code !== 200) {
		// 	$todayIP.html(`<tr><td colspan="6" class="text-center">获取地址失败</td></tr>`)
		// 	console.error('获取地址失败:', addresResult)
		// 	return
		// }

		// 临时方法: 合并地址
		// data.forEach(item => {
		// 	const address = addresResult.data.find(i => i.query === item.ip)
			
		// 	if (address && address.status === 'success') {
		// 		item.address =  address.regionName + ' ' + address.city
		// 	} else {
		// 		item.address = '未知'
		// 	}
		// })
		
		data.forEach((item, index) => {
			const chinaTime = dayjs(item.accessTime).tz('Asia/Shanghai')
			const formattedTime = chinaTime.format('YYYY年MM月DD日 HH:mm:ss')

			uap.setUA(item.ua)
			const { browser, os } = uap.getResult()

			tr += `
				<tr class="text-center align-middle">
					<td>${item.id}</td>
					<td class="xf_ip_${index}">${item.ip} <span></span></td>
					<td>${item.pv}</td>
					<td>${os.name ? os.name + '系统' : '未知系统'}${browser.name ? browser.name + '浏览器' : '未知浏览器'}</td>
					<td>${formattedTime}</td>
					<td>
						<div class="btn-group btn-group-sm">
							<a class="btn btn-default" href="JavaScript:;" data-bs-toggle="tooltip" title="移除" onclick="del('${str}', ${item.id})"><i class="mdi mdi-window-close"></i></a>
						</div>
					</td>
				</tr>
			`
		})

		$todayIP.html(tr)
		
		totalPage = total && total > 0 ? Math.ceil(total / pageSize) : 1

		// 更新分页按钮
		renderPagination(str, page, totalPage) // 这里应该使用 currentPage

		// 删除loading
		$loadingDom.hide()

		// 渲染工具
		renderTooltip()
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.error('服务器有误: ', error)
		$todayIP.html(`<tr><td colspan="6" class="text-center">服务器有误, 请检查控制台查看原因</td></tr>`)
		// 删除loading
		$loadingDom.hide()
	}
}

// 渲染分页按钮
function renderPagination(str, currentPage, totalPage) {
	let pageHtml = ''
	$paginationDom.html('加载中...')

	// 上一页
	pageHtml += `<li class="page-item ${currentPage === 1 || totalPage === 0 ? 'disabled' : ''}">
		<a class="page-link" href="javascript:void(0);" onclick="selectPageNumber('${str}', ${currentPage - 1})">上一页</a>
	</li>`

	// 如果总页数大于 10，则只显示上一页和下一页
	if (totalPage > 10) {
		pageHtml += `<li class="page-item ${currentPage === totalPage || totalPage === 0 ? 'disabled' : ''}">
			<a class="page-link" href="javascript:void(0);" onclick="selectPageNumber('${str}', ${currentPage + 1})">下一页</a>
		</li>`
	} else {
		// 页码按钮
		for (let i = 1; i <= totalPage; i++) {
			pageHtml += `<li class="page-item ${currentPage === i ? 'active' : ''}">
				<a class="page-link" href="javascript:void(0);" onclick="selectPageNumber('${str}', ${i})">${i}</a>
			</li>`
		}

		// 下一页
		pageHtml += `<li class="page-item ${currentPage === totalPage || totalPage === 0 ? 'disabled' : ''}">
			<a class="page-link" href="javascript:void(0);" onclick="selectPageNumber('${str}', ${currentPage + 1})">下一页</a>
		</li>`
	}

	$paginationDom.html(pageHtml)
}

// 选择页数
function selectPageNumber(str, num) {
	if (num < 1 || num > totalPage || totalPage === 0) {
		return
	}
	page = num
	getIp(str, page)
}

// 删除ip
async function del(str, id) {
	if (!id) {
		showNotify('参数不得为空', 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
		return
	}

	try {
		const response = await $.ajax({
			url: `${apiPath}del?id=${id}`,
			method: 'GET',
			dataType: 'json'
		})
		const { code, msg } = response

		if (code !== 200) {
			showNotify(msg, 'info', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		showNotify(msg, 'success', 5000, 'mdi mdi-check-circle', 'top', 'right')
		getIp(str, page)
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.log('服务器有误: ', error)
	}
}

// 批量删除ip
async function deleteIp(str) {
	if (!str) {
		showNotify('参数不得为空', 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
		return
	}

	if (str !== 'today' && str !== 'aDay' && str !== 'all') {
		showNotify('参数有误', 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
		return
	}

	try {
		const isDelRes = await swal({
			title: '确定删除么',
			text: '',
			icon: 'info',
			buttons: ['取消', '确定'],
			dangerMode: true,
		})

		if (!isDelRes) {
			return
		}

		const response = await $.ajax({
			url: `${apiPath}del?isTady=${str}`,
			method: 'GET',
			dataType: 'json'
		})

		const { code, msg } = response

		if (code !== 200) {
			showNotify(msg, 'info', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		showNotify(msg, 'success', 5000, 'mdi mdi-check-circle', 'top', 'right')
		getIp('today')
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.log('服务器有误: ', error)
	}
}

// 访问配置
const $accessConfigurationForm = $('#accessConfigurationForm')
const $expirationTime = $('#expirationTime')
const $accessTime = $('#accessTime')
const $numberOfVisits = $('#numberOfVisits')
const $shield = $('#shield')

// 同步时间
const $syncMinutes = $('#syncMinutes')
const $setSyncMinutes = $('#setSyncMinutes')

// 渲染访问配置
async function renderAccessConfig() {
	try {
		const response = await fetch(`${apiPath}getRestrictedInfo`)
		const { code, data, msg } = await response.json()
		if (code !== 200) {
			showNotify(msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		$expirationTime.val(data.expirationTime)
		$accessTime.val(data.accessTime)
		$numberOfVisits.val(data.numberOfVisits)
		$shield.val(data.shield)
	} catch (error) {
		console.error(error)
		showNotify('表单数据渲染失败', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
}

// 获取表单信息
$accessConfigurationForm.submit(async function (e) {
	e.preventDefault()

	const formData = $(this).serializeArray()

	const obj = formData.reduce((acc, { name, value }) => {
		acc[name] = Number(value)
		return acc
	}, {})

	try {
		const { msg, code } = await $.ajax({
			url: `${apiPath}setRestrictedInfo`,
			method: 'POST',
			data: obj
		})

		if (code !== 200) {
			showNotify(msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		showNotify(msg, 'success', 5000, 'mdi mdi-check-circle', 'top', 'right')
		renderAccessConfig()
	} catch (error) {
		console.error('服务器有误: ', error)
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
})

// 渲染同步时间
async function renderSynchronizationTime() {
	try {
		const response = await fetch(`${apiPath}getSyncIPTime`)
		const { code, data, msg } = await response.json()
		if (code !== 200) {
			showNotify(msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}
		$syncMinutes.val(data)
	} catch (error) {
		console.error(error)
		showNotify('表单数据渲染失败', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
}

// 保存同步时间
$setSyncMinutes.on('click', async () => {
	if (!$syncMinutes.val()) {
		showNotify('同步时间不得为空', 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
		return
	}
	try {
		const { msg, code } = await $.ajax({
			url: `${apiPath}setSyncIPTime`,
			method: 'POST',
			data: { syncMinutes: $syncMinutes.val() }
		})
		if (code !== 200) {
			showNotify(msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}
		showNotify(msg, 'success', 5000, 'mdi mdi-check-circle', 'top', 'right')
		renderSynchronizationTime()
	} catch (error) {
		console.error('服务器有误: ', error)
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
})

async function synchronizationTime() {
	try {
		const { msg, code } = await $.ajax({
			url: `${apiPath}synchronizationIP`,
			method: 'GET',
		})

		if (code !== 200) {
			showNotify(msg, 'warning', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		showNotify(msg, 'success', 5000, 'mdi mdi-check-circle', 'top', 'right')
		getIp('today')
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
	}
}

$(document).ready(function (e) {
	renderAccessConfig()
	renderSynchronizationTime()
	getIp('today')
})